//
//  FFRecvVM.m
//  LLWallet
//
//  Created by tt on 2020/12/16.
//

#import "FFRecvVM.h"
#import "FFRecvCardCell.h"
#import "FFRecvSetAmountVC.h"
#import "FFRecvSetAmountVC.h"
#import "FFRecvTotalHeadCell.h"
#import "FFRecvRecordVC.h"
#import "FFRecvPayUserItemCell.h"
#import "FFWalletConst.h"
@interface FFRecvVM ()<WKCMDManagerDelegate,WKChannelManagerDelegate>

@property(nonatomic,copy) NSString *qrcode;
@property(nonatomic,assign) NSInteger amount; // 设置的金额
@property(nonatomic,copy) NSString *remark;

@property(nonatomic,strong) NSMutableArray<FFRecvUserItemModel*> *payUsers;


@end

@implementation FFRecvVM

- (instancetype)init
{
    self = [super init];
    if (self) {
        [[WKSDK shared].cmdManager addDelegate:self];
        [[WKSDK shared].channelManager addDelegate:self];
    }
    return self;
}

- (void)dealloc {
    [[WKSDK shared].cmdManager removeDelegate:self];
    [[WKSDK shared].channelManager removeDelegate:self];
}


-(NSArray<NSDictionary*>*) tableSectionMaps {
    BOOL loading = true;
    if(self.qrcode) {
        loading = false;
    }
    __weak typeof(self) weakSelf = self;
    NSMutableArray *userItems = [NSMutableArray array];
    
    NSInteger totalAmount = 0;
    if(self.payUsers.count>0) {
        NSInteger i = 0;
        for (FFRecvUserItemModel *userModel in self.payUsers) {
            totalAmount += (NSInteger)(userModel.amount.floatValue*100);
            [userItems addObject:@{
                @"class": FFRecvPayUserItemModel.class,
                @"amount": [NSString stringWithFormat:@"¥%@",userModel.amount],
                @"name": userModel.name?:@"",
                @"avatar": [WKAvatarUtil getAvatar:userModel.uid],
                @"bottomCorner": @(i==self.payUsers.count-1),
            }];
            i++;
        }
    }
    
    return @[
        @{
            @"height":@(10.0f),
            @"items":@[
                    @{
                        @"class": FFRecvCardModel.class,
                        @"loading":@(loading),
                        @"amount":@(self.amount),
                        @"remark":self.remark?:@"",
                        @"qrcode": self.qrcode?:@"",
                        @"bottomNoCorner":@(self.payUsers.count>0),
                        @"onSetAmount":^{
                            if(weakSelf.amount>0) {
                                weakSelf.amount = 0.0f;
                                weakSelf.remark = @"";
                                [weakSelf requestQRCode];
                            }else{
                                FFRecvSetAmountVC *vc = [FFRecvSetAmountVC new];
                                vc.onNext = ^(NSString * _Nonnull amountText, NSString * _Nonnull remark) {
                                    if(amountText && ![amountText isEqualToString:@""]) {
                                        weakSelf.amount = [WKMoneyUtil yuan2Penny:@(amountText.floatValue)].intValue;
                                    }
                                    weakSelf.remark = remark;
                                    [weakSelf requestQRCode];
                                };
                                [[WKNavigationManager shared] pushViewController:vc animated:YES];
                            }
                           
                        },
                        @"onRecord":^{
                            FFRecvRecordVC *vc = [FFRecvRecordVC new];
                            [[WKNavigationManager shared] pushViewController:vc animated:YES];
                        }
                    }
            ],
        },
        @{
            @"height":@(0.0f),
            @"items": @[
                    @{
                        @"class": FFRecvTotalHeadModel.class,
                        @"hidden": @(self.payUsers.count<=0),
                        @"amount": [WKMoneyUtil penny2YuanFormat:@(totalAmount)],
                    }
            ],
        },
        @{
            @"height":@(0.0f),
            @"items": userItems,
        }
    ];
}

-(AnyPromise*) requestQRCode {
    __weak typeof(self) weakSelf = self;
    return [[WKAPIClient sharedClient] POST:@"impay/recvpay/recv/qrcode" parameters:@{
        @"amount":@(weakSelf.amount),
        @"remark": weakSelf.remark?:@"",
    }].then(^(NSDictionary *result){
        weakSelf.qrcode = result[@"qrcode"];
        weakSelf.expire = result[@"expire"]?[result[@"expire"] integerValue]:60;
        [weakSelf reloadData];
    });
}

- (NSMutableArray<FFRecvUserItemModel *> *)payUsers {
    if(!_payUsers) {
        _payUsers = [NSMutableArray array];
    }
    return _payUsers;
}

#pragma mark -- WKCMDManagerDelegate

-(void) cmdManager:(WKCMDManager*)manager onCMD:(WKCMDModel*)model {
    
    if([model.cmd isEqualToString:LIMCMD_RECEIVE_MONEY_SUCCESS]) { // 收款成功
        FFRecvUserItemModel *userModel = [FFRecvUserItemModel new];
        userModel.uid = model.param[@"uid"]?:@"";
        userModel.amount = model.param[@"amount"]?:@"";
        WKChannelInfo*channelInfo = [[WKSDK shared].channelManager getChannelInfo:[WKChannel personWithChannelID:userModel.uid]];
        if(channelInfo) {
            userModel.name = channelInfo.displayName;
        }
        [self.payUsers insertObject:userModel atIndex:0];
        if(!channelInfo) {
            [[WKSDK shared].channelManager fetchChannelInfo:[WKChannel personWithChannelID:userModel.uid]];
        }
        [self reloadData];
    }
}

#pragma mark -- WKChannelManagerDelegate

- (void)channelInfoUpdate:(WKChannelInfo *)channelInfo {
    
    if(self.payUsers && self.payUsers.count>0) {
        BOOL needReload = false;
        for (FFRecvUserItemModel *userModel in self.payUsers) {
            if([userModel.uid isEqualToString:channelInfo.channel.channelId]) {
                userModel.name = channelInfo.displayName;
                needReload = true;
            }
        }
        if(needReload) {
            [self reloadData];
        }
    }
}

-(UIImage*) imageName:(NSString*)name {
    return [[WKApp shared] loadImage:name moduleID:@"LLWallet"];
}


@end

@implementation FFRecvUserItemModel


@end
